/**
 * Simulator
 */
var Simulator = function() {
	var buttonElems = {
		polyline: "#toolbar-polyline",
		zone: "#toolbar-zone",
		obstruction: "#toolbar-obstruction",
		spawn: "#toolbar-spawn",
		endpoint: "#toolbar-endpoints",
		route: "#toolbar-route",
		geocode: "#geocode-btn",
		toolbar: "#toolbar-radios",
		save: "#toolbar-save"
	};

	var startpointOptions = {
		color: "00FF00",
		text: "Start",
		type: "start"
	};

	var endpointOptions = {
		color: "FF0000",
		text: "End",
		type: "end"
	};

	var obstructionOptions = {
		polyoptions: {
			strokeWeight: 2,
			fillColor: "#5555FF"
		},
		type: "obstruction"
	};

	var zoneOptions = {
		polyoptions: {
			strokeWeight: 2,
			fillColor: "#000000"
		},
		type: "zone"
	};

	var polylineOptions = {
		strokeColor: '#FFD700',
		strokeOpacity: 1.0,
		strokeWeight: 4,
	};

	/**
	 * Build jquery ui buttons
	 */
	function buttons() {
		//$(buttonElems.zone).button({ icons: { primary: "ui-icon-disk" } });
		//$(buttonElems.obstruction).button({ icons: { primary: "ui-icon-gear" } });
		$(buttonElems.save).button({ icons: { primary: "ui-icon-gear" } });

		$(buttonElems.spawn).button({
			text: false,
			icons: { primary: "ui-icon-person" }
		});

		/*
		$(buttonElems.endpoint).button({
			text: false,
			icons: { primary: "ui-icon-flag" }
		});

		$(buttonElems.route).button({
			icons: { primary: "ui-icon-flag" }
		});
		*/

		// Geocode search button
		$(buttonElems.geocode).button({ icons: { primary: "ui-icon-search"} });
		// Radio buttons
		$(buttonElems.toolbar).buttonset();
	}

	/**
	 * Create modal forms - the login and registration forms are from built-in 
	 * django views.
	 */
	function modalForms() {
		/**
		* Login modal form
		*/
		$("#login-dialog").dialog({
			autoOpen: false,
			height: 250,
			width: 350,
			modal: true,
			buttons: {
				close: function() {
					$(this).dialog('close')
				},

				login: function() {
					$.ajax({
						type: "POST",
						url: "/accounts/login/",
						data: $("#login-form").serialize(),
						success: function(data) {
							var errors = $(data).find("#login-error").val();
							if (errors) {
								$("#error-message").replaceWith("<p class='error'>" + "Your username and password didn't match" + "</p>");
							} else {
								window.location = "/builder";
							}
						}
					});
				} 
			}
		});

		$("#login").click(function() {
			$("#login-dialog").load("/accounts/login").dialog("open");
		});

		/**
		 * Registration form
		 */
		$("#register-dialog").dialog({
			autoOpen: false,
			height: 325,
			width: 800,
			modal: true,
			buttons: {
				close: function() {
					$(this).dialog('close')
				},
				create: function() {
					$.ajax({
						type: "POST",
						url: "/register/",
						data: $("#registration-form").serialize(),
						success: function(data) {
							// Check and see if any errors are present
							var html = $(data).find(".errorlist");
							// If there are errors present, rebuild the dialog with the output from view
							if (html) {
								$("#register-dialog").html(data);
							} else {
								window.location = "/builder";
							}
						}
					});
				} 
			}
		});
		$("#register").click(function() {
			$("#register-dialog").load("/register/").dialog("open");
		});
	}

	function initialize() {
		var myMap = Map();
		var map = myMap.init();
		var simData = SimData(map);
		buttons();
		modalForms();

		// Place CSRF header before any ajax request is sent
		$.ajaxSetup({
			beforeSend: function(xhr, settings) {
				if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
					// Only send the token to relative URLs i.e. locally.
					xhr.setRequestHeader("X-CSRFToken",
										$("#csrfmiddlewaretoken").val());
				}
			}
    	});

    	$("#id_username").keypress(function(event) {
    		if (event.which == 13) {
    			event.preventDefault();
				console.log("enter");
			}
		});

		/**
		 * Draw polyline
		 */
		$(buttonElems.polyline).button({
			icons: { 
				primary: "ui-icon-pencil"
			}
		}).click(function() {
			google.maps.event.clearListeners(map);

			var polyline = new google.maps.Polyline(polylineOptions);
			polyline.setMap(map);

			var markers = [];

			google.maps.event.addListener(map, 'click', function(e) {
				polylineOptions.position = e.latLng;
				var marker = simData.placePolyline(polylineOptions, polyline, markers);
				
				google.maps.event.addListener(marker, 'click', function(markerClick) {
					google.maps.event.clearListeners(map);
					var firstpoint = markerClick.latLng;
					
					polylineOptions.position = markerClick.latLng;
					// Start a new polyline from the current marker
					var branch = new google.maps.Polyline(polylineOptions);
					branch.setMap(map);

					google.maps.event.addListener(map, 'click', function(mapClick) {

						polylineOptions.position = mapClick.latLng;
						var branchMarker = simData.placePolyline(polylineOptions, branch, markers);
						var branchPath = branch.getPath();
						var marker = new StyledMarker({
							styleIcon: new StyledIcon(
								StyledIconTypes.MARKER, {
									//color:"AED6EC"
									color:"2d2d2d"
								}),
							//position: event.latLng,
							position: e.position,
							map: map,
							title: '#' + path.getLength(),
							draggable: true
						});

						branchPath.push(marker.position);
						
						//console.log(marker.position);
					});
				});
			});
		});

		/*
		$(buttonElems.polyline).click(function() {
			google.maps.event.clearListeners(map);

			var polyline = new google.maps.Polyline(polyLineOptions);
			polyline.setMap(map);
			
			var polyline = simData.drawPolyline(polyLineOptions);
			var markers = [];

			google.maps.event.addListener(map, 'click', function(e) {
				polyLineOptions.position = e.latLng;
				simData.placePolyline(polyLineOptions, polyline, markers);
			});
		});
		*/

		/**
		 * Draw obstruction
		 */
		$(buttonElems.obstruction).click(function() {
			google.maps.event.clearListeners(map);

			var path = simData.drawShape(obstructionOptions);
			var markers = [];
			google.maps.event.addListener(map, 'click', function(e) {
				obstructionOptions.position = e.latLng;
				simData.placeShapePath(obstructionOptions, path, markers);
			});
			/*
			 * call drawShape, then on map click call placePath?
			google.maps.event.addListener(map, 'click', function(e) {
				obstructionOptions.position = e.latLng;
				simData.drawShape(obstructionOptions);
			});
			*/
		});

		/**
		 * Draw zone
		 */
		$(buttonElems.zone).click(function() {
			google.maps.event.clearListeners(map);

			var path = simData.drawShape(zoneOptions);
			var markers = [];
			google.maps.event.addListener(map, 'click', function(e) {
				zoneOptions.position = e.latLng;
				simData.placeShapePath(zoneOptions, path, markers);
			});
		});

		/**
		 * Generate street route
		 */
		$(buttonElems.route).click(function() {
			simData.sendOverlays();
			//console.log(simData.getzones()[0][0].lat());
			//console.log(simData.getzones()[0][0].lng());
			/*
			if (spawnPoints.length != 0 && endPoints.length != 0) {
				var position = {
					origin: spawnPoints.toString(),
					dest: endPoints.toString()
				};
				simData.directions(position);
			}
			*/
		});

		/**
		 * Add Spawn point
		 */
		$(buttonElems.spawn).click(function() {
			google.maps.event.clearListeners(map);
			google.maps.event.addListener(map, 'click', function(e) {
				startpointOptions.position = e.latLng;
				simData.placeMarker(startpointOptions);
				simData.saveState();
			});
		});

		/**
		 * Place end point
		 */
		$(buttonElems.endpoint).click(function() {
			google.maps.event.clearListeners(map);
			google.maps.event.addListener(map, 'click', function(e) {
				endpointOptions.position = e.latLng;
				simData.placeMarker(endpointOptions);
				simData.saveState();
			});
		});

		// Load overlays from cookies
		(function() {

			//Load startpoint and endpoints from cookie
			function loadPoints(type, options) {
				if ($.cookie(type)) {
					var mypoints = JSON.parse($.cookie(type));
					for (var i = 0; i < mypoints.length; i++) {
						var latLng = new google.maps.LatLng(mypoints[i].lat, mypoints[i].lng);
						options.position = latLng;
						simData.placeMarker(options);
					}
				}
			}

			// Load shapes from cookie
			function loadShapes(type) {
				if ($.cookie(type)) {
					var myshapes = JSON.parse($.cookie(type));
					for (var i = 0; i < myshapes.length; i++) {
						
						var currentShape = myshapes[i].coords;

						if (myshapes[i].type === 'zone') {
							var options = zoneOptions;
							var path = simData.drawShape(zoneOptions);
							var markers = [];
						} else {
							var options = obstructionOptions;
							var path = simData.drawShape(obstructionOptions);
							var markers = [];
						}

						for (var j = 0; j < currentShape.length; j++) {
							var lat = currentShape[j].lat;
							var lng = currentShape[j].lng;
							options.position = new google.maps.LatLng(lat, lng);
							simData.placeShapePath(options, path, markers);
						}
					}
				}
			}

			function loadInfoWindows(type) {
				if ($.cookie(type)) {
					var windows = JSON.parse($.cookie(type));
					/*
					for (var i = 0; i < windows.length; i++) {
						var infowindow = new google.maps.InfoWindow({
							content: windows[i].content
						});

						infowindow.setPosition(
							new google.maps.LatLng(windows[i].lat, windows[i].lng)
						);
						infowindow.open(map);
					}
					*/
				}
			}

			loadShapes('allShapes');
			loadPoints('startpoints', startpointOptions);
			loadPoints('endpoints', endpointOptions);
			loadInfoWindows('infowindows');

		})()
	}


	/**
	 * Public methods
	 */
	return {
		init: function() {
			initialize();
		}
	};
};

/**
 * Execute on window ready
 */
$(function() {
	simulator = Simulator();
	simulator.init();	
});
